package com.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 每个半小时去获取微信令牌
 *  令牌是有时间限制2个小时
 *  还有次数限制2000次/天
 */
@Component
public class WeixinTokenTask {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weixin.appid}")
    private  String appid;

    @Value("${weixin.secret}")
    private  String secret;

    @Autowired


    private RedisTemplate redisTemplate;

    @Scheduled(initialDelay = 2, fixedRate  = 180000)
    public  void updateToken()
    {
       String url =  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
       String newUrl = String.format(url,appid,secret);
       String result = restTemplate.getForObject(newUrl,String.class);
       String token = JSONObject.parseObject(result).getString("access_token");
       redisTemplate.boundValueOps("token").set(token);
       //System.out.println(token);

    }



}
